<!DOCTYPE html>
<html lang=zh>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="description" content="浏览器渲染过程 从上图可以看出 浏览器的重绘主要有以下过程：  解析HTML，生成DOM树，解析CSS，生成CSSOM树 将DOM树和CSSOM树结合，生成渲染树(Render Tree) Layout(回流):根据生成的渲染树，进行回流(Layout)，得到节点的几何信息（位置，大小） Painting(重绘):根据渲染树以及回流得到的几何信息，得到节点的绝对像素 Display:将像素发送给G">
<meta property="og:type" content="article">
<meta property="og:title" content="重绘与回流">
<meta property="og:url" content="https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/index.html">
<meta property="og:site_name" content="柯里的语法糖">
<meta property="og:description" content="浏览器渲染过程 从上图可以看出 浏览器的重绘主要有以下过程：  解析HTML，生成DOM树，解析CSS，生成CSSOM树 将DOM树和CSSOM树结合，生成渲染树(Render Tree) Layout(回流):根据生成的渲染树，进行回流(Layout)，得到节点的几何信息（位置，大小） Painting(重绘):根据渲染树以及回流得到的几何信息，得到节点的绝对像素 Display:将像素发送给G">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://codertzm.oss-cn-chengdu.aliyuncs.com/image-20211127193930366.png">
<meta property="og:image" content="https://codertzm.oss-cn-chengdu.aliyuncs.com/render-tree-construction.png">
<meta property="article:published_time" content="2022-03-05T12:31:10.768Z">
<meta property="article:modified_time" content="2022-03-15T02:59:24.904Z">
<meta property="article:author" content="柯里的语法糖">
<meta property="article:tag" content="你好啊">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://codertzm.oss-cn-chengdu.aliyuncs.com/image-20211127193930366.png">
    
    
      
        
          <link rel="shortcut icon" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
      
        
          <link rel="icon" type="image/png" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico" sizes="192x192">
        
      
      
        
          <link rel="apple-touch-icon" sizes="180x180" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
    
    <!-- title -->
    <title>重绘与回流</title>
    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">

    <!-- persian styles -->
    
    <!-- rss -->
    
    
	<!-- mathjax -->
	
<meta name="generator" content="Hexo 6.0.0"></head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" aria-label="Top" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" aria-label="上一篇" href="/2022/03/05/frontend/%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE%E7%9A%84%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" aria-label="下一篇" href="/2022/03/05/JavaScript/array/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" aria-label="返回顶部" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" aria-label="分享文章" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&text=重绘与回流"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&is_video=false&description=重绘与回流"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=重绘与回流&body=Check out this article: https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&name=重绘与回流&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&t=重绘与回流"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E8%BF%87%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">浏览器渲染过程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E6%B8%B2%E6%9F%93%E6%A0%91"><span class="toc-number">2.</span> <span class="toc-text">生成渲染树</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9E%E6%B5%81"><span class="toc-number">3.</span> <span class="toc-text">回流</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%87%8D%E7%BB%98"><span class="toc-number">4.</span> <span class="toc-text">重绘</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%95%E6%97%B6%E5%8F%91%E7%94%9F%E5%9B%9E%E6%B5%81%E9%87%8D%E7%BB%98"><span class="toc-number">5.</span> <span class="toc-text">何时发生回流重绘</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E4%BC%98%E5%8C%96%E6%9C%BA%E5%88%B6"><span class="toc-number">6.</span> <span class="toc-text">浏览器优化机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%8F%E5%B0%91%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98"><span class="toc-number">7.</span> <span class="toc-text">减少回流与重绘</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%80%E5%B0%8F%E5%8C%96%E5%9B%9E%E6%B5%81%E5%92%8C%E9%87%8D%E7%BB%98"><span class="toc-number">7.1.</span> <span class="toc-text">最小化回流和重绘</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9DOM"><span class="toc-number">7.2.</span> <span class="toc-text">批量修改DOM</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%85%8D%E8%A7%A6%E5%8F%91%E5%90%8C%E6%AD%A5%E5%B8%83%E5%B1%80%E4%BA%8B%E4%BB%B6"><span class="toc-number">7.3.</span> <span class="toc-text">避免触发同步布局事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E4%BA%8E%E5%A4%8D%E6%9D%82%E5%8A%A8%E7%94%BB%E6%95%88%E6%9E%9C-%E4%BD%BF%E7%94%A8%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E8%AE%A9%E5%85%B6%E8%84%B1%E7%A6%BB%E6%96%87%E6%A1%A3%E6%B5%81"><span class="toc-number">7.4.</span> <span class="toc-text">对于复杂动画效果,使用绝对定位让其脱离文档流</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8css%E7%A1%AC%E4%BB%B6%E5%8A%A0%E9%80%9F"><span class="toc-number">7.5.</span> <span class="toc-text">使用css硬件加速</span></a></li></ol></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        重绘与回流
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">柯里的语法糖</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2022-03-05T12:31:10.768Z" itemprop="datePublished">2022-03-05</time>
        
      
    </div>


      

      

    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <h2 id="浏览器渲染过程"><a href="#浏览器渲染过程" class="headerlink" title="浏览器渲染过程"></a>浏览器渲染过程</h2><p><img src="https://codertzm.oss-cn-chengdu.aliyuncs.com/image-20211127193930366.png" alt="image-20211127193930366"></p>
<p>从上图可以看出 浏览器的重绘主要有以下过程：</p>
<ol>
<li>解析HTML，生成DOM树，解析CSS，生成CSSOM树</li>
<li>将DOM树和CSSOM树结合，生成渲染树(Render Tree)</li>
<li>Layout(回流):根据生成的渲染树，进行回流(Layout)，得到节点的几何信息（位置，大小）</li>
<li>Painting(重绘):根据渲染树以及回流得到的几何信息，得到节点的绝对像素</li>
<li>Display:将像素发送给GPU，展示在页面上。（这一步其实还有很多内容，比如会在GPU将多个合成层合并为同一个层，并展示在页面中。而css3硬件加速的原理则是新建合成层）</li>
</ol>
<h2 id="生成渲染树"><a href="#生成渲染树" class="headerlink" title="生成渲染树"></a>生成渲染树</h2><p><img src="https://codertzm.oss-cn-chengdu.aliyuncs.com/render-tree-construction.png"></p>
<p>为了生成渲染树，浏览器主要做了如下工作：</p>
<ol>
<li>从DOM树的根节点开始遍历每个<strong>可见节点</strong>。</li>
<li>对于每个可见的节点，找到CSSOM树中对应的规则，并应用它们。</li>
<li>根据每个可见节点以及其对应的样式，组合生成渲染树。</li>
</ol>
<p><strong>什么是不可见节点</strong>：</p>
<ul>
<li>一些不会渲染输出的节点，比如script、meta、link等。</li>
<li>一些通过css进行隐藏的节点。比如display:none。注意，利用visibility和opacity隐藏的节点，还是会显示在渲染树上的。只有display:none的节点才不会显示在渲染树上。</li>
</ul>
<blockquote>
<p>渲染树只包含可见的节点</p>
</blockquote>
<h2 id="回流"><a href="#回流" class="headerlink" title="回流"></a>回流</h2><p>我们通过构造渲染树，我们将可见DOM节点以及它对应的样式结合起来，可是我们还需要计算它们在设备视口(viewport)内的确切位置和大小，这个计算的阶段就是回流。</p>
<p>为了弄清每个对象在网站上的确切大小和位置，浏览器从渲染树的根节点开始遍历，我们可以以下面这个实例来表示：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width,initial-scale=1&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Critial Path: Hello world!<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&quot;width: 50%&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&quot;width: 50%&quot;</span>&gt;</span>Hello world!<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>第一个div将节点的显示尺寸设置为视口宽度的50%，第二个div将其尺寸设置为父节点的50%。而在回流这个阶段，我们就需要根据视口具体的宽度，将其转为实际的像素值。</p>
<h2 id="重绘"><a href="#重绘" class="headerlink" title="重绘"></a>重绘</h2><p>我们通过构造渲染树和回流阶段，我们知道了哪些节点是可见的，以及可见节点的样式和具体的几何信息(位置、大小)，那么我们就可以<strong>将渲染树的每个节点都转换为屏幕上的实际像素</strong> ，这个阶段就叫做重绘节点。</p>
<h2 id="何时发生回流重绘"><a href="#何时发生回流重绘" class="headerlink" title="何时发生回流重绘"></a>何时发生回流重绘</h2><p>回流这一阶段主要是计算节点的位置和几何信息，那么当页面布局和几何信息发生变化的时候，就需要回流。比如以下情况：</p>
<ul>
<li>添加或删除可见的DOM元素</li>
<li>元素的位置发生变化</li>
<li>元素的尺寸发生变化（包括外边距、内边距、边框大小、高度和宽度等）</li>
<li>内容发生变化，比如文本变化或图片被另一个不同尺寸的图片所替代。</li>
<li>页面一开始渲染的时候（这肯定避免不了）</li>
<li>浏览器的窗口尺寸变化（因为回流是根据视口的大小来计算元素的位置和大小的）</li>
</ul>
<blockquote>
<p>回流一定会触发重绘，而重绘不一定会回流</p>
</blockquote>
<h2 id="浏览器优化机制"><a href="#浏览器优化机制" class="headerlink" title="浏览器优化机制"></a>浏览器优化机制</h2><p>现代的浏览器都是很聪明的，由于每次重排都会造成额外的计算消耗，因此大多数浏览器都会通过队列化修改并批量执行来优化重排过程。浏览器会将修改操作放入到队列里，直到过了一段时间或者操作达到了一个阈值，才清空队列。但是，当你获取布局信息的操作的时候，会强制队列刷新，比如当你访问以下属性或者使用以下方法：</p>
<ul>
<li>offsetTop、offsetLeft、offsetWidth、offsetHeight</li>
<li>scrollTop、scrollLeft、scrollWidth、scrollHeight</li>
<li>clientTop、clientLeft、clientWidth、clientHeight</li>
<li>getComputedStyle()</li>
<li>getBoundingClientRect</li>
</ul>
<p>以上属性和方法都需要返回最新的布局信息，因此浏览器不得不清空队列，触发回流重绘来返回正确的值。因此，我们在修改样式的时候，<strong>最好避免使用上面列出的属性，他们都会刷新渲染队列。</strong>如果要使用它们，最好将值缓存起来。</p>
<h2 id="减少回流与重绘"><a href="#减少回流与重绘" class="headerlink" title="减少回流与重绘"></a>减少回流与重绘</h2><p>接下来说一说如何减少回流和重绘</p>
<h3 id="最小化回流和重绘"><a href="#最小化回流和重绘" class="headerlink" title="最小化回流和重绘"></a>最小化回流和重绘</h3><p>为了减少发生次数，我们可以合并多次对DOM和样式的修改，然后一次处理掉。考虑这个例子</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> el = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;test&#x27;</span>);</span><br><span class="line">el.style.padding = <span class="string">&#x27;5px&#x27;</span>;</span><br><span class="line">el.style.borderLeft = <span class="string">&#x27;1px&#x27;</span>;</span><br><span class="line">el.style.borderRight = <span class="string">&#x27;2px&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p>例子中，有三个样式属性被修改了，每一个都会影响元素的几何结构，引起回流。当然，大部分现代浏览器都对其做了优化，因此，只会触发一次重排。但是如果在旧版的浏览器或者在上面代码执行的时候，有其他代码访问了布局信息(上文中的会触发回流的布局信息)，那么就会导致三次重排。</p>
<p>因此，我们可以合并所有的改变然后依次处理，比如我们可以采取以下的方式：</p>
<ul>
<li><p>使用cssText</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> el = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;test&#x27;</span>);</span><br><span class="line">el.style.cssText += <span class="string">&#x27;border-left: 1px; border-right: 2px; padding: 5px;&#x27;</span>;</span><br></pre></td></tr></table></figure></li>
<li><p>修改css的class</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> el = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;test&#x27;</span>);</span><br><span class="line">el.className += <span class="string">&#x27; active&#x27;</span>;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="批量修改DOM"><a href="#批量修改DOM" class="headerlink" title="批量修改DOM"></a>批量修改DOM</h3><p>当我们需要对DOM对一系列修改的时候，可以通过以下步骤减少回流重绘次数：</p>
<ol>
<li>使元素脱离文档流</li>
<li>对其进行多次修改</li>
<li>将元素带回到文档中。</li>
</ol>
<p>该过程的第一步和第三步可能会引起回流，但是经过第一步之后，对DOM的所有修改都不会引起回流重绘，因为它已经不在渲染树了。</p>
<p><strong>有三种方式可以使元素脱离文档流：</strong></p>
<ul>
<li>隐藏元素，应用修改，重新显示</li>
<li>使用文档片段(document fragment)在当前DOM之外构建一个子树，再把它拷贝回文档。</li>
<li>将原始元素拷贝到一个脱离文档的节点中，修改节点后，再替换原始的元素。</li>
</ul>
<p>考虑我们要执行一段批量插入节点的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">appendDataToElement</span>(<span class="params">appendToElement, data</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> li;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; data.length; i++) &#123;</span><br><span class="line">     li = <span class="built_in">document</span>.createElement(<span class="string">&#x27;li&#x27;</span>);</span><br><span class="line">        li.textContent = <span class="string">&#x27;text&#x27;</span>;</span><br><span class="line">        appendToElement.appendChild(li);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> ul = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;list&#x27;</span>);</span><br><span class="line">appendDataToElement(ul, data);</span><br></pre></td></tr></table></figure>

<p>如果我们直接这样执行的话，由于每次循环都会插入一个新的节点，会导致浏览器回流一次。</p>
<p>可以使用下面这三种方式进行优化：</p>
<ul>
<li><p>隐藏元素</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">appendDataToElement</span>(<span class="params">appendToElement, data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> li;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; data.length; i++) &#123;</span><br><span class="line">   li = <span class="built_in">document</span>.createElement(<span class="string">&#x27;li&#x27;</span>);</span><br><span class="line">      li.textContent = <span class="string">&#x27;text&#x27;</span>;</span><br><span class="line">      appendToElement.appendChild(li);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> ul = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;list&#x27;</span>);</span><br><span class="line">ul.style.display = <span class="string">&#x27;none&#x27;</span>;</span><br><span class="line">appendDataToElement(ul, data);</span><br><span class="line">ul.style.display = <span class="string">&#x27;block&#x27;</span>;</span><br></pre></td></tr></table></figure></li>
</ul>
<p>在展示和隐藏的时候，会产生两次回流</p>
<ul>
<li>应用修改</li>
</ul>
<p>使用文档片段(document Fragment) ，在当前DOM之外构建一个子树，<code>createDocumentFragment</code>，再把它拷贝回文档</p>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> ul = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;list&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fragment = <span class="built_in">document</span>.createDocumentFragment();</span><br><span class="line">appendDataToElement(fragment, data);</span><br><span class="line">ul.appendChild(fragment);</span><br></pre></td></tr></table></figure>

<ul>
<li>重新显示</li>
</ul>
<p>将原始元素拷贝到一个脱离文档的节点中，修改节点后，再替换原始的元素。</p>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> ul = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;list&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> clone = ul.cloneNode(<span class="literal">true</span>);</span><br><span class="line">appendDataToElement(clone, data);</span><br><span class="line">ul.parentNode.replaceChild(clone, ul);</span><br></pre></td></tr></table></figure>

<p>但是经过测试，性能提升并不大，因为现代浏览器会使用队列来储存多次修改，进行优化，所以对这个优化方案，我们其实不用优先考虑。</p>
<h3 id="避免触发同步布局事件"><a href="#避免触发同步布局事件" class="headerlink" title="避免触发同步布局事件"></a>避免触发同步布局事件</h3><p>上文我们说过，当我们访问元素的一些属性的时候，会导致浏览器强制清空队列，进行强制同步布局。举个例子，比如说我们想将一个p标签数组的宽度赋值为一个元素的宽度，我们可能写出这样的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initP</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; paragraphs.length; i++) &#123;</span><br><span class="line">        paragraphs[i].style.width = box.offsetWidth + <span class="string">&#x27;px&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这段代码看上去是没有什么问题，可是其实会造成很大的性能问题。在每次循环的时候，都读取了box的一个<strong>offsetWidth</strong>属性值，然后利用它来更新p标签的width属性。这就导致了每一次循环的时候，浏览器都必须先使上一次循环中的样式更新操作生效，才能响应本次循环的样式读取操作。每一次循环都会强制浏览器刷新队列。我们可以优化为:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> width = box.offsetWidth;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initP</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; paragraphs.length; i++) &#123;</span><br><span class="line">        paragraphs[i].style.width = width + <span class="string">&#x27;px&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="对于复杂动画效果-使用绝对定位让其脱离文档流"><a href="#对于复杂动画效果-使用绝对定位让其脱离文档流" class="headerlink" title="对于复杂动画效果,使用绝对定位让其脱离文档流"></a>对于复杂动画效果,使用绝对定位让其脱离文档流</h3><p>对于复杂动画效果，由于会经常的引起回流重绘，因此，我们可以使用绝对定位，让它脱离文档流。否则会引起父元素以及后续元素频繁的回流。</p>
<h3 id="使用css硬件加速"><a href="#使用css硬件加速" class="headerlink" title="使用css硬件加速"></a>使用css硬件加速</h3><ol>
<li>使用css3硬件加速，可以让 transform、opacity、filters 这些动画不会引起回流重绘</li>
<li>对于动画的其它属性，比如 background-color 这些，还是会引起回流重绘的，不过它还是可以提升这些动画的性能</li>
</ol>
<p><strong>css3硬件加速的坑</strong>：</p>
<ul>
<li>如果你为太多元素使用css3硬件加速，会导致内存占用较大，会有性能问题。</li>
<li>在GPU渲染字体会导致抗锯齿无效。这是因为GPU和CPU的算法不同。因此如果你不在动画结束的时候关闭硬件加速，会产生字体模糊。</li>
</ul>

  </div>
</article>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/search/">搜索</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E8%BF%87%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">浏览器渲染过程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E6%B8%B2%E6%9F%93%E6%A0%91"><span class="toc-number">2.</span> <span class="toc-text">生成渲染树</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9E%E6%B5%81"><span class="toc-number">3.</span> <span class="toc-text">回流</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%87%8D%E7%BB%98"><span class="toc-number">4.</span> <span class="toc-text">重绘</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%95%E6%97%B6%E5%8F%91%E7%94%9F%E5%9B%9E%E6%B5%81%E9%87%8D%E7%BB%98"><span class="toc-number">5.</span> <span class="toc-text">何时发生回流重绘</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E4%BC%98%E5%8C%96%E6%9C%BA%E5%88%B6"><span class="toc-number">6.</span> <span class="toc-text">浏览器优化机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%8F%E5%B0%91%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98"><span class="toc-number">7.</span> <span class="toc-text">减少回流与重绘</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%80%E5%B0%8F%E5%8C%96%E5%9B%9E%E6%B5%81%E5%92%8C%E9%87%8D%E7%BB%98"><span class="toc-number">7.1.</span> <span class="toc-text">最小化回流和重绘</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9DOM"><span class="toc-number">7.2.</span> <span class="toc-text">批量修改DOM</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%85%8D%E8%A7%A6%E5%8F%91%E5%90%8C%E6%AD%A5%E5%B8%83%E5%B1%80%E4%BA%8B%E4%BB%B6"><span class="toc-number">7.3.</span> <span class="toc-text">避免触发同步布局事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E4%BA%8E%E5%A4%8D%E6%9D%82%E5%8A%A8%E7%94%BB%E6%95%88%E6%9E%9C-%E4%BD%BF%E7%94%A8%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E8%AE%A9%E5%85%B6%E8%84%B1%E7%A6%BB%E6%96%87%E6%A1%A3%E6%B5%81"><span class="toc-number">7.4.</span> <span class="toc-text">对于复杂动画效果,使用绝对定位让其脱离文档流</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8css%E7%A1%AC%E4%BB%B6%E5%8A%A0%E9%80%9F"><span class="toc-number">7.5.</span> <span class="toc-text">使用css硬件加速</span></a></li></ol></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&text=重绘与回流"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&is_video=false&description=重绘与回流"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=重绘与回流&body=Check out this article: https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&title=重绘与回流"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&name=重绘与回流&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/03/05/frontend/%E5%9B%9E%E6%B5%81%E4%B8%8E%E9%87%8D%E7%BB%98/&t=重绘与回流"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy;
    
    
    2021-2022
    柯里的语法糖
  </div>
  <div class="footer-right">
    <nav>
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </nav>
  </div>
</footer>

    </div>
    <!-- styles -->



  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" crossorigin="anonymous" onload="this.onload=null;this.rel='stylesheet'"/>


    <!-- jquery -->
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script> 




<!-- clipboard -->

  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.7/clipboard.min.js" crossorigin="anonymous"></script> 
  
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"复制到粘贴板!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "复制成功!");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

<!-- Cloudflare Analytics -->

<!-- Umami Analytics -->

<!-- Disqus Comments -->

<!-- utterances Comments -->

</body>
</html>
